package com.luocc.ccdemo.common

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.luocc.ccdemo.R
import com.luocc.ccdemo.entity.Blog

private const val TAG = "LC_BlogListAdapter"

class BlogListAdapter(private val context: Context) :
    ListAdapter<Blog, RecyclerView.ViewHolder>(MyDiffCallback()) {

    private var mItemClickListener: OnItemClickListener<Blog>? = null

    class MyDiffCallback : DiffUtil.ItemCallback<Blog>() {
        override fun areItemsTheSame(oldItem: Blog, newItem: Blog): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: Blog, newItem: Blog): Boolean {
            return oldItem == newItem
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val v = LayoutInflater.from(context).inflate(R.layout.item_blog, parent, false)
        return BlogHolder(v)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val title = holder.itemView.findViewById<TextView>(R.id.title)
        val sender = holder.itemView.findViewById<TextView>(R.id.sender)
        val time = holder.itemView.findViewById<TextView>(R.id.time)
        title.text = getItem(position).title
        sender.text = getItem(position).sender
        time.text = getItem(position).time
        if (position and 1 == 1) {
            holder.itemView.background =
                AppCompatResources.getDrawable(context, R.drawable.bg_item_blog_a)
        } else {
            holder.itemView.background =
                AppCompatResources.getDrawable(context, R.drawable.bg_item_blog_b)
        }
        holder.itemView.setOnClickListener {
            mItemClickListener?.onClick(position, getItem(position))
        }
    }

    fun setOnItemClickListener(listener: OnItemClickListener<Blog>) {
        mItemClickListener = listener
    }

    private class BlogHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}